package com.spider.lwlk.mysql.task

import com.spider.lwlk.mongodb.task.taskstatus.TaskStatus
import groovy.sql.BatchingPreparedStatementWrapper
import groovy.sql.Sql

class ContractTask extends BaseTask {

    private static final Isbn_regex = [
            /<div class="show_info_right max_width">(\d+)<\/div>/,
            /<li>国际标准书号ISBN：(\d+)<\/li>/
    ]

    private html, isbns = []

    @Override def onSuccess() {

        {   resp, reader ->

            taskStatus = TaskStatus.RequestSuccess

            html = reader.text

            isbns = getISBNs()

            doUpdate()
        }
    }

    private getISBNs() {

        Isbn_regex.each { regex -> html.eachMatch(regex) { m -> isbns += m[1] } }

        isbns.unique().sort()
    }

    @Override def onFilter() {

        {   Sql db ->

            isbns = isbns.findAll() { isbn -> !db.firstRow("select * from isbn_table where isbn = ? limit 1", [isbn]) }
        }
    }

    @Override def onUpdate() {

        {   Sql db ->

            db.withBatch("insert into isbn_table(isbn) values(?)") { BatchingPreparedStatementWrapper ps ->

                isbns.each { isbn -> ps.addBatch([isbn]) }
            }

            taskStatus = TaskStatus.UpdateSuccess
        }
    }

    @Override def onCompleted() {

        {   Sql db ->

            db.execute("delete from book_url_table where url = ?", [path])

            db.executeInsert("insert into book_url_check_table(url, html) values(?, ?)", [path, html])

            taskStatus = TaskStatus.Success
        }
    }
}
